﻿using Autofac.Core;
using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace FreeDream.WebApi
{
    /// <summary>
    /// Autofac注册ControllerBase
    /// </summary>
    public class AutofacPropertityModuleReg : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            //这里设置哪些程序集可以进行属性注入，默认控制器即可

            // 获取所有控制器类型并使用属性注入
            var controllerBaseType = typeof(ControllerBase);
            //先暂时获取这里的程序集，之后改造通过option进行配置
            builder.RegisterAssemblyTypes(typeof(Program).Assembly) //Assembly.Load("DataPlatform.Admin.WebApi")
                .Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
                .PropertiesAutowired();

        }
    }

    public class AutowiredPropertySelector : IPropertySelector
    {
        public bool InjectProperty(PropertyInfo propertyInfo, object instance)
        {
            return propertyInfo.CustomAttributes.Any(it => it.AttributeType == typeof(AutowiredAttribute));
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class AutowiredAttribute : System.Attribute
    {
    }
}
